package com.heima.app.gateway;

import com.heima.utils.common.AppJwtUtil;
import io.jsonwebtoken.Claims;
import org.apache.commons.lang.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.net.URI;

@Component
@Order(1)
public class filter implements GlobalFilter {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpResponse response = exchange.getResponse();
        ServerHttpRequest request = exchange.getRequest();
        //1.获取请求url
        String uri = request.getURI().getPath();
        //2.判断url是否是登录地址
        if(uri.contains("/login_auth")) {
            //3.是:放行
            return chain.filter(exchange);
        }
        //4.否：判断用户是否进行登录
        //4.1 判断请求头中是否携带了token
        String token = request.getHeaders().getFirst("token");
        if(StringUtils.isEmpty(token)) {
            //4.2 未携带：响应401状态码，拦截
            //响应401状态码
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            //拦截
            return response.setComplete();
        }
        //4.3 携带：校验令牌合法性。
        try {
            Claims claims = AppJwtUtil.getClaimsBody(token);
            //将用户id存入请求头放行
            Integer id = claims.get("id", Integer.class);
            if (id!=0){
                request.mutate().header("userId",String.valueOf(id));
            }
            //4.3.1 合法：放行
            return chain.filter(exchange);
        } catch (Exception e) {
            e.printStackTrace();
            //4.3.2 不合法：响应401状态码，拦截
            //响应401状态码
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            //拦截
            return response.setComplete();
        }

    }
}
